<?php

  /**
   * This class provides all method needed to interact with an ODBC datasource.<br />
   * Connect to a datasource.<br />
   *
   * @param string $dsn The database source name for the connection.
   * @param string $login The username.
   * @param string $password The password.
   * @param integer $cursor_type  This sets the type of cursor to be used for
   * this connection. This parameter is not normally needed, but can be useful
   * for working around problems with some ODBC drivers.<br />
   * The following constants are defined for cursortype : SQL_CUR_USE_IF_NEEDED,
   * SQL_CUR_USE_ODBC, SQL_CUR_USE_DRIVER and SQL_CUR_DEFAULT.
   *
   * @see <a href="http://fr2.php.net/manual/en/function.odbc-connect.php">odbc_connect()</a>
   */
  class ODBCLink extends Base {
    /** @var resource The credential use for the current connection. */
    private $Resource = NULL;

    /** @var string The database source name for the connection. */
    private $dsn = "";

    /** @var string The username. */
    private $login = "";

    /** @var string The password. */
    private $password = "";

    /**
     * Connect to a datasource.<br />
     *
     * @param string $dsn The database source name for the connection.
     * @param string $login The username.
     * @param string $password The password.
     * @param integer $cursor_type This sets the type of cursor to be used for
     * this connection. This parameter is not normally needed, but can be useful
     * for working around problems with some ODBC drivers.<br />
     * The following constants are defined for cursortype : SQL_CUR_USE_IF_NEEDED,
     * SQL_CUR_USE_ODBC, SQL_CUR_USE_DRIVER and SQL_CUR_DEFAULT.
     *
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-connect.php">odbc_connect()</a>
     */
    public function __construct($dsn, $login, $password, $cursor_type = NULL) {
      $this->dsn = $dsn;
      $this->login = $login;
      $this->password = $password;

      if (! empty($cursor_type))
        $this->Resource = odbc_connect($dsn, $login, $password, $cursor_type);
      else
        $this->Resource = odbc_connect($dsn, $login, $password);
    }

    /**
     * This property define if the driver is connected or not.<br />
     * @return boolean TRUE if connected.
     */
    public function isConnected() {
      return ! empty($this->Resource);
    }

    /**
     * Returns the current DSN.
     * @return string The database source name for the connection.
     */
    public function getDSN() {
      return $this->dsn;
    }

    /**
     * Returns the login.
     * @return string The user name.
     */
    public function getLogin() {
      return $this->login;
    }

    /**
     * Returns the password.
     * @return string The password.
     */
    public function getPassword() {
      return $this->password;
    }

    /**
     * Sets the DSN for the connection.<br />
     * @param string $value The database source name for the connection.
     */
    public function setDSN($value) {
      $this->dsn = $value;
    }

    /**
     * Sets the login.<br />
     * @param string $value The user name.
     */
    public function setLogin($value) {
      $this->login = $value;
    }

    /**
     * Sets the password.<br />
     * @param string $value The password.
     */
    public function setPassword($value) {
      $this->password = $value;
    }

    /**
     * Toggle autocommit behaviour.
     * By default, auto-commit is on for a connection. Disabling auto-commit is
     * equivalent with starting a transaction.<br />
     *
     * @param boolean $value If $value is TRUE, auto-commit is enabled, if it is
     * FALSE auto-commit is disabled.
     *
     * @return mixed Returns auto-commit status for the current connection.<br />
     * Non-zero is returned if auto-commit is on, 0 if it is off, or FALSE if an
     * error occurs.<br /><br />
     *
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-autocommit.php">odbc_autocommit()</a>
     */
    public function getAutoCommit() {
      return odbc_autocommit($this->Resource);
    }

    /**
     * Toggle autocommit behaviour.
     * By default, auto-commit is on for a connection. Disabling auto-commit is
     * equivalent with starting a transaction.<br />
     *
     * @param boolean $value If $value is TRUE, auto-commit is enabled, if it is
     * FALSE auto-commit is disabled.
     *
     * @return boolean Returns TRUE on success and FALSE on failure.<br /><br />
     *
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-autocommit.php">odbc_autocommit()</a>
     */
    public function setAutoCommit($value) {
      return odbc_autocommit($this->Resource, $value);
    }

    /**
     * Handling of binary column data.<br />
     * Enables handling of binary column data. ODBC SQL types affected are
     * BINARY, VARBINARY, and LONGVARBINARY.<br />
     * When binary SQL data is converted to character C data, each byte (8 bits)
     * of source data is represented as two ASCII characters.<br />
     * These characters are the ASCII character representation of the number in
     * its hexadecimal form. For example, a binary 00000001 is converted to "01"
     * and a binary 11111111 is converted to "FF".<br />
     * If FetchInto() is used, passthru means that an empty string is returned
     * for these columns.<br />
     *
     * @param resource $Result The result identifier.
     * @param integer $mode Possible values for $mode are : <br /><br />
     * ODBC_BINMODE_PASSTHRU: Passthru BINARY data<br />
     * ODBC_BINMODE_RETURN: Return as is<br />
     * ODBC_BINMODE_CONVERT: Convert to char and return<br />

     * @return boolean Returns TRUE on success or FALSE on failure.<br /><br />
     *
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-binmode.php">odbc_binmode()</a>
     */
    public function setBinMode($Result, $mode) {
      return odbc_binmode($Result, $mode);
    }

    /**
     * Adjust ODBC settings.<br />
     * This function allows fiddling with the ODBC options for a particular
     * connection or query result.<br />
     * It was written to help find work around to problems in quirky ODBC drivers.<br /><br />
     * You should probably only use this function if you are an ODBC programmer
     * and understand the effects the various options will have.<br />
     * You will certainly need a good ODBC reference to explain all the
     * different options and values that can be used.<br /><br />
     * Different driver versions support different options.<br />
     * Because the effects may vary depending on the ODBC driver, use of this
     * function in scripts to be made publicly available is strongly discouraged.<br />
     * Also, some ODBC options are not available to this function because they
     * must be set before the connection is established or the query is prepared.<br />
     * However, if on a particular job it can make PHP work so your boss
     * doesn't tell you to use a commercial product, that's all that really matters.<br />
     *
     * @param integer $function Is the ODBC function to use. The value should be
     * 1 for SQLSetConnectOption() and 2 for SQLSetStmtOption().
     *
     * @param integer $option The option to set.
     * @param integer $param The value for the given option
     * .
     * @return boolean Returns TRUE on success or FALSE on failure.<br /><br />
     *
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-setoption.php">odbc_setoption()</a>
     */
    public function setOption($function, $option, $param) {
      return odbc_setoption($this->Resource, $function, $option, $param);
    }

    /**
     * Close an ODBC connection.<br />
     * Closes down the connection to the database server.<br />
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-close.php">odbc_close()</a>
     */
    public function Close() {
      odbc_close($this->Resource);

      $this->Resource = NULL;
    }

    /**
     * Commit an ODBC transaction.<br />
     * Commits all pending transactions on the connection.<br />
     * @return boolean Returns TRUE on success or FALSE on failure.<br /><br />
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-commit.php">odbc_commit()</a>
     */
    public function Commit() {
      return odbc_commit($this->Resource);
    }

    /**
     * Open a persistent database connection.<br />
     * The connection is not really closed when the script has finished.
     * Future requests for a connection with the same dsn, user and password
     * combination (via ConnectPersistent()) can reuse the persistent connection.<br />
     *
     * @param string $dsn The database source name for the connection.
     * @param string $user The user name.
     * @param string $password the password.
     * @param integer $cursor_type This sets the type of cursor to be used for
     * this connection. This parameter is not normally needed, but can be useful
     * for working around problems with some ODBC drivers.<br />
     * The following constants are defined for cursortype : SQL_CUR_USE_IF_NEEDED,
     * SQL_CUR_USE_ODBC, SQL_CUR_USE_DRIVER and SQL_CUR_DEFAULT.
     *
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-pconnect.php">odbc_pconnect()</a>
     */
    public function ConnectPersistent($dsn,
                                      $user,
                                      $password,
                                      $cursor_type = NULL) {
      if (! empty($cursor_type))
        $this->Resource = odbc_pconnect($dsn, $user, $password, $cursor_type);
      else
        $this->Resource = odbc_pconnect($dsn, $user, $password);
    }

    /**
     * Returns information about a current connection.<br />
     * This function will return the list of available DNS (after calling it several times). <br />
     *
     * @param integer $fetch_type Use SQL_FETCH_FIRST the first time this
     * function is called, thereafter use the SQL_FETCH_NEXT.
     *
     * @return mixed Returns FALSE on error, and an array upon success.<br /><br />
     *
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-data-source.php">odbc_data_source()</a>
     */
    public function DataSource($fetch_type) {
      return odbc_data_source($this->Resource, $fetch_type);
    }

    /**
     * Prepare and execute a SQL statement.<br />
     * Sends an SQL statement to the database server.<br />
     *
     * @param string $query The SQL statement.
     * @param integer $flags Not documented.
     *
     * @return mixed Returns an ODBC result identifier if the SQL command was
     * executed successfully, or FALSE on error.<br /><br />
     *
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-exec.php">odbc_exec()</a>
     */
    public function Execute($query, $flags = NULL) {
      if (! empty($flags))
        return odbc_exec($this->Resource, $query, $flags);
      else
        return odbc_exec($this->Resource, $query);
    }

    /**
     * Execute a prepared statement.<br />
     * Executes a statement prepared with Prepare().<br />
     *
     * @param array $parameters Parameters in $parameters will be substituted
     * for placeholders in the prepared statement in order. Elements of this
     * array will be converted to strings by calling this function.<br /><br />
     * Any parameters in $parameter which start and end with single quotes will
     * be taken as the name of a file to read and send to the database server as
     * the data for the appropriate placeholder.<br /><br />
     * If you wish to store a string which actually begins and ends with single
     * quotes, you must add a space or other non-single-quote character to the
     * beginning or end of the parameter, which will prevent the parameter from
     * being taken as a file name. If this is not an option, then you must use
     * another mechanism to store the string, such as executing the query
     * directly with odbc_exec()).
     *
     * @return boolean Returns TRUE on success or FALSE on failure.<br /><br />
     *
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-execute.php">odbc_execute()</a>
     */
    public function ExecuteStatement($parameters = NULL) {
      if (! empty($parameters))
        return odbc_execute($this->Resource, $parameters);
      else
        return odbc_execute($this->Resource);
    }

    /**
     * Print result as HTML table.<br />
     * Prints all rows from a result identifier produced by Execute().<br />
     * The result is printed in HTML table format.<br />
     *
     * @param resource $Result The result identifier.
     * @param string $format Additional overall table formatting.
     *
     * @return integer Returns the number of rows in the result or FALSE on error.<br /><br />
     *
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-result-all.php">odbc_result_all()</a>
     */
    public function GetAllResult($Result, $format = NULL) {
      if (! empty($format))
        return odbc_result_all($Result, $format);
      else
        return odbc_result_all($Result);
    }

    /**
     * Lists the column names in specified tables.<br />
     * Lists all columns in the requested range.<br />
     *
     * @param string $qualifier The qualifier.
     * @param string $schema The owner.
     * @param string $table The table name.
     * @param string $column The column name.
     *
     * @return mixed Returns an ODBC result identifier or FALSE on failure.<br />
     * The result set has the following columns : TABLE_QUALIFIER, TABLE_SCHEM,
     * TABLE_NAME, COLUMN_NAME, DATA_TYPE, TYPE_NAME, PRECISION, LENGTH, SCALE,
     * RADIX, NULLABLE and REMARKS.<br />
     * The result set is ordered by TABLE_QUALIFIER, TABLE_SCHEM and TABLE_NAME.<br /><br />
     *
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-columns.php">odbc_columns()</a>
     */
    public function GetColumns($qualifier = NULL,
                               $schema = NULL,
                               $table = NULL,
                               $column = NULL) {
      if (! empty($column))
        return odbc_columns($this->Resource, $qualifier, $schema, $table, $column);
      else
        if (! empty($table))
          return odbc_columns($this->Resource, $qualifier, $schema, $table);
        else
          if (! empty($schema))
            return odbc_columns($this->Resource, $qualifier, $schema);
          else
            if (! empty($qualifier))
              return odbc_columns($this->Resource, $qualifier);
            else
              return odbc_columns($this->Resource);
    }

    /**
     * Lists columns and associated privileges for the given table.<br />
     *
     * @param string $qualifier The qualifier.
     * @param string $owner The owner.
     * @param string $table The table name.
     * @param string $column The $column argument accepts search patterns
     * ('%' to match zero or more characters and '_' to match a single character).
     *
     * @return mixed Returns an ODBC result identifier or FALSE on failure.<br />
     * This result identifier can be used to fetch a list of columns and
     * associated privileges.<br />
     * The result set has the following columns : TABLE_QUALIFIER, TABLE_OWNER,
     * TABLE_NAME, GRANTOR, GRANTEE, PRIVILEGE and IS_GRANTABLE.<br />
     * The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.<br /><br />
     *
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-columnprivileges.php">odbc_columnprivileges()</a>
     */
    public function GetColumnPrivileges($qualifier, $owner, $table, $column) {
      return odbc_columnprivileges($this->Resource,
                                   $qualifier,
                                   $owner,
                                   $table,
                                   $column);
    }

    /**
     * Number of rows in a result.<br />
     * Gets the number of rows in a result.<br />
     * For INSERT, UPDATE and DELETE statements GetNumRows() returns the number
     * of rows affected.<br />
     * For a SELECT clause this can be the number of rows available.<br />
     *
     * @param resource $Result The result identifier returned by Execute().
     *
     * @return integer Returns the number of rows in an ODBC result. This
     * function will return -1 on error.<br /><br />
     *
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-num-rows.php">odbc_num_rows()</a>
     */
    public function GetNumberOfRows($Result) {
      return odbc_num_rows($Result);
    }

    /**
     * Gets the primary keys for a table.<br />
     * Returns a result identifier that can be used to fetch the column names
     * that comprise the primary key for a table.<br />
     *
     * @param string $qualifier The qualifier.
     * @param string $owner The owner.
     * @param string $table The table name.
     *
     * @return mixed Returns an ODBC result identifier or FALSE on failure.<br />
     * The result set has the following columns : TABLE_QUALIFIER, TABLE_OWNER,
     * TABLE_NAME, COLUMN_NAME, KEY_SEQ and  PK_NAME.<br /><br />
     *
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-primarykeys.php">odbc_primarykeys()</a>
     */
    public function GetPrimaryKeys($qualifier, $owner, $table) {
      return odbc_primarykeys($this->Resource, $qualifier, $owner, $table);
    }

    /**
     * Get the list of procedures stored in a specific data source.<br />
     * Lists all procedures in the requested range.<br />
     *
     * @param string $qualifier The qualifier.
     * @param string $owner The owner. This parameter accepts the following
     * search patterns: "%" to match zero or more characters, and "_" to match
     * a single character.
     * @param string $name The name. This parameter accepts the following search
     * patterns: "%" to match zero or more characters, and "_" to match a
     * single character.
     *
     * @return mixed Returns an ODBC result identifier containing the
     * information or FALSE on failure.<br />
     * The result set has the following columns : PROCEDURE_QUALIFIER, PROCEDURE_OWNER,
     * PROCEDURE_NAME, NUM_INPUT_PARAMS, NUM_OUTPUT_PARAMS, NUM_RESULT_SETS,
     * REMARKS and PROCEDURE_TYPE.<br /><br />
     *
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-procedures.php">odbc_procedures()</a>
     */
    public function GetProcedures($qualifier = NULL,
                                  $owner = NULL,
                                  $name = NULL) {
      if (! empty($qualifier) && ! empty($owner) && ! empty($name))
        return odbc_procedures($this->Resource, $qualifier, $owner, $name);
      else
        return odbc_procedures($this->Resource);
    }

    /**
     * Retrieve information about parameters to procedures.<br />
     *
     * @param string $qualifier The qualifier.
     * @param string $owner The owner. This parameter accepts the following
     * search patterns: "%" to match zero or more characters, and "_" to match
     * a single character.
     * @param string $procedure The proc. This parameter accepts the following
     * search patterns: "%" to match zero or more characters, and "_" to match
     * a single character.
     * @param string $column The column. This parameter accepts the following
     * search patterns: "%" to match zero or more characters, and "_" to match
     * a single character.
     *
     * @return mixed  Returns the list of input and output parameters, as well
     * as the columns that make up the result set for the specified procedures.
     * Returns an ODBC result identifier or FALSE on failure.<br /><br />
     * The result set has the following columns : PROCEDURE_QUALIFIER, PROCEDURE_OWNER,
     * PROCEDURE_NAME, COLUMN_NAME, COLUMN_TYPE, DATA_TYPE, TYPE_NAME, PRECISION,
     * LENGTH, SCALE, RADIX, NULLABLE and REMARKS.<br /><br />
     * The result set is ordered by PROCEDURE_QUALIFIER, PROCEDURE_OWNER,
     * PROCEDURE_NAME and COLUMN_TYPE. <br /><br />
     *
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-procedurecolumns.php">odbc_procedurecolumns()</a>
     */
    public function GetProceduresParameters($qualifier = NULL,
                                            $owner = NULL,
                                            $procedure = NULL,
                                            $column = NULL) {
      if (! empty($qualifier) && ! empty($owner) && ! empty($procedure) && ! empty($column))
        return odbc_procedurecolumns($this->Resource, $qualifier, $owner, $procedure, $column);
      else
        return odbc_procedurecolumns($this->Resource);
    }

    /**
     * Get result data.<br />
     *
     * @param resource $Result The ODBC resource.
     * @param mixed $field The field name being retrieved. It can either be an
     * integer containing the column number of the field you want; or it can be
     * a string containing the name of the field.
     *
     * @return mixed Returns the string contents of the field, FALSE on error,
     * NULL for NULL data, or TRUE for binary data.<br /><br />
     *
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-result.php">odbc_result()</a>
     */
    public function GetResult($Result, $field) {
      return odbc_result($Result, $field);
    }

    /**
     * Prepares a statement for execution.<br />
     * The result identifier can be used later to execute the statement with
     * Execute().<br />
     * Some databases (such as IBM DB2, MS SQL Server, and Oracle) support
     * stored procedures that accept parameters of type IN, INOUT, and OUT as
     * defined by the ODBC specification. However, the Unified ODBC driver
     * currently only supports parameters of type IN to stored procedures.<br />
     *
     * @param string $query The query string statement being prepared.
     * @return mixed Returns an ODBC result identifier if the SQL command was
     * prepared successfully. Returns FALSE on error.<br /><br />
     *
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-prepare.php">odbc_prepare()</a>
     */
    public function Prepare($query) {
      return odbc_prepare($this->Resource, $query);
    }

    /**
     * Rollback a transaction.<br />
     * Rolls back all pending statements on the connection.<br />
     * @return boolean Returns TRUE on success or FALSE on failure.<br /><br />
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-rollback.php">odbc_rollback()</a>
     */
    public function RollBack() {
      return odbc_rollback($this->Resource);
    }

    /**
     * Retrieves special columns.<br />
     * Retrieves either the optimal set of columns that uniquely identifies a
     * row in the table, or columns that are automatically updated when any
     * value in the row is updated by a transaction.<br />
     *
     * @param integer $type When the type argument is SQL_BEST_ROWID,
     * odbc_specialcolumns() returns the column or columns that uniquely
     * identify each row in the table.   When the type argument is SQL_ROWVER,
     * odbc_specialcolumns() returns the column or columns in the specified
     * table, if any, that are automatically updated by the data source when any
     * value in the row is updated by any transaction.
     *
     * @param string $qualifier The qualifier.
     * @param string $owner The owner.
     * @param string $table The table.
     * @param integer $scope The scope, which orders the result set.
     * @param integer $nullable The nullable option.
     *
     * @return mixed Returns an ODBC result identifier or FALSE on failure.<br />
     * The result set has the following columns : SCOPE, COLUMN_NAME, DATA_TYPE,
     * TYPE_NAME, PRECISION, LENGTH, SCALE and PSEUDO_COLUMN.<br /><br />
     *
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-specialcolumns.php">odbc_specialcolumns()</a>
     */
    public function SpecialColumns($type,
                                   $qualifier,
                                   $owner,
                                   $table,
                                   $scope,
                                   $nullable) {
      return odbc_specialcolumns($this->Resource,
                                 $type,
                                 $qualifier,
                                 $owner,
                                 $table,
                                 $scope,
                                 $nullable); }

    /**
     * Retrieve statistics about a table.<br />
     * Get statistics about a table and its indexes.<br />
     *
     * @param string $qualifier The qualifier.
     * @param string $owner The owner.
     * @param string $table the table.
     * @param integer $unique The unique attribute.
     * @param integer $accuracy The accuracy.
     *
     * @return mixed Returns an ODBC result identifier or FALSE on failure.<br />
     * The result set has the following columns : TABLE_QUALIFIER, TABLE_OWNER,
     * TABLE_NAME, NON_UNIQUE, INDEX_QUALIFIER, INDEX_NAME, TYPE, SEQ_IN_INDEX,
     * COLUMN_NAME, COLLATION, CARDINALITY, PAGES and FILTER_CONDITION.<br />
     * The result set is ordered by NON_UNIQUE, TYPE, INDEX_QUALIFIER,
     * INDEX_NAME and SEQ_IN_INDEX.<br /><br />
     *
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-statistics.php">odbc_statistics()</a>
     */
    public function Statistics($qualifier, $owner, $table, $unique, $accuracy) {
      return odbc_statistics($this->Resource,
                             $qualifier,
                             $owner,
                             $unique,
                             $accuracy);
    }

    /**
     * Fetch a result row as an associative array.<br />
     * Fetch an associative array from an ODBC query.<br />
     * @param resource $result The result resource from Execute().
     * @return mixed Returns an array that corresponds to the fetched row, or
     * FALSE if there are no more rows.<br /><br />
     * @see <a href="http://fr2.php.net/manual/en/function.odbc-fetch-array.php">odbc_fetch_array()</a>
     */
    public function FetchArray($result) {
      return odbc_fetch_array($result);
    }
  }
?>
